package com.springboot.exceptions;


import com.springboot.enums.CodeEnum;
import com.springboot.exceptions.message.SimpleMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author tang
 */
@SuppressWarnings("Duplicates")
@Slf4j
@ControllerAdvice
public class WebExceptionHandler {
    /**
     * 不支持
     */
    private final static String NOT_SUPPORTED = "not supported";
    /**
     * 缺少参数
     */
    private final static String INVALID_PARAMS = "parameter";

    /**
     * 自定义异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = ErrorCodeException.class)
    @ResponseBody
    public SimpleMessage myErrorHandler(HttpServletRequest request, ErrorCodeException e) {
        SimpleMessage message = new SimpleMessage();
        log.error("[{}]接口异常[{}]", request.getRequestURI(), e.getMessage());
        message.setCode(e.getCode());
        message.setMsg(e.getMessage());
        return message;
    }

    /**
     * 系统异常
     *
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public SimpleMessage errorHandler(HttpServletRequest request, Exception ex) {
        SimpleMessage message = new SimpleMessage();
        log.error("[{}]系统异常", request.getRequestURI(), ex);
        // 请求方式错误
        if (ex.getMessage().contains(NOT_SUPPORTED)) {
            return new SimpleMessage(CodeEnum.NOT_SUPPORT);
        } else if (ex.getMessage().contains(INVALID_PARAMS)) {
            return new SimpleMessage(CodeEnum.INVALID_PARAMS);
        }
        message.setCode(CodeEnum.ERROR.getCode());
        message.setMsg(CodeEnum.ERROR.getMessage());
        return message;
    }
}